# Greg Johnston
#  <greg.johnston@gmail.com>
#  config.py
#  Class and methods for storing configuration information

import os

class RitualConfig:
	"""All the configuration information for a Ritual user"""
	def __init__(self):
		self.config = {"default_file" : None,
					   "tmp_dir": self.default_tmp(),
					   "view" : "gtk"}
		self.load_config()

	def config_file(self):
		"""Returns the file to be used for config"""
		if os.name == "nt" or os.name == "ce": # Windows NT or CE
			return os.environ.get("USERPROFILE")+"Local Settings\Application Data\Ritual\config.txt"
		elif os.name == "posix": # Posix
			return os.environ.get("HOME")+"/.ritual/config"
		else: # OS Unknown (riscos, os2, etc.)
			return None

	def load_config(self):
		"""Loads configuration from a file depending on the OS"""
		cfile = self.config_file()
		try:
			f = open(cfile, "r")
		except IOError (errno):
			if errno == 2: # File does not exist
				open(cfile, "w").close() # Create the file
				f = open(cfile, "r")
		lines = f.readlines()
		for line in lines:
			part = line.partition(":") # ex.: ("default_file", ":", " greg.ritual")
			key = part[0].strip() # Get rid of any whitespace
			value = part[2].strip() # Get rid of the newline + any whitespace
			if value == "<NONE>":
				pass # Default values loaded already
			else:		
				self.config[key] = value

	def save_config(self):
		"""Saves configuration back to file"""
		cfile = self.config_file()
		f = open(cfile, "w")
		for key in self.config.keys():
			if self.config[key] == None:
				f.write(key+": <NONE>\n")
			else:
				f.write(key+": "+self.config[key]+"\n")
		f.close()

	def default_tmp(self):
		"""Returns the name of the default temporary directory"""
		if os.path.isdir("/tmp"):
			return "/tmp/"
		elif os.getenv("temp"):
			return os.getenv("temp")
		else:
			return None

	def get_view(self):
		"""Returns the object for the type of view in the config"""
		if self.config["view"] == "gtk":
			from gtkview import GTKView
			return GTKView()
		else:
			print "Only GTK view is supported at the moment. Please fix your configuration file."
			self.quit(1)
		
